package org.javaymw.springboot.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.javaymw.springboot.base.BaseController;
import org.javaymw.springboot.base.servlet.ServletUtil;
import org.javaymw.springboot.dto.RoleDto;
import org.javaymw.springboot.dto.UserDto;
import org.javaymw.springboot.dto.UserRoleDto;
import org.javaymw.springboot.service.RoleService;
import org.javaymw.springboot.service.UserRoleService;
import org.javaymw.springboot.service.UserService;
import org.javaymw.springboot.shiro.PasswordHelper;
import org.javaymw.springboot.task.AsyncTask;
import org.javaymw.springboot.util.MessageUtils;
import org.javaymw.springboot.view.PoiExcelExport;
import org.javaymw.springboot.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 描述：用户管理
 * <p>
 * Author: 赵新国
 * Date: 2017/11/14 15:21
 */
@Controller
@RequestMapping("/admin/user")
public class AdminUserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private AsyncTask asyncTask;

    /**
     * 分页查询用户列表
     * @param model
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@RequestParam(value="pageNum", defaultValue="1") int pageNum,
                       @RequestParam(value="pageSize", defaultValue="10") int pageSize,
                       @RequestParam(required = false) String searchParam,
                       @RequestParam(required = false) String startDate,
                       @RequestParam(required = false) String endDate, Model model) {
        Page<UserDto> userDtos = userService.getUserByPage(pageNum, pageSize, searchParam, startDate, endDate);
        PageInfo<UserDto> page = new PageInfo<UserDto>(userDtos);
        model.addAttribute("page",page);
        // 参数回显
        model.addAttribute("userName", searchParam);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        return "admin/user/userList";
    }

    @GetMapping(value = "/tree")
    @ResponseBody
    public Map<String, Object> tree() {
        Map<String, Object> retMap = MessageUtils.success();
        try {
            List<UserDto> userDtos = userService.list();
            retMap.put("userDtos", userDtos);
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 导出用户信息
     *
     * @param userName
     * @return
     */
    @GetMapping(value = "/export")
    public void export(@RequestParam String userName, HttpServletRequest request, HttpServletResponse response) {
        long start = System.currentTimeMillis();
        String fileName = "用户数据.xls";
        ServletUtil su = new ServletUtil(fileName, request, response);
        su.poiExcelServlet();
        String[] heads = {"用户名","密码","手机号","邮箱"};
        String[] cols = {"userName","passWord","phone","email"};
        int[] numerics = {2};
        List<UserDto> userDtos = userService.listUsers(userName);
        if (userDtos == null || userDtos.isEmpty()) {
            return;
        }
        ServletUtil suresp = new ServletUtil(response);
        PoiExcelExport pee = new PoiExcelExport(fileName, heads, cols, userDtos, numerics, suresp.getOut());
        pee.exportExcel();
        long end = System.currentTimeMillis();
        logger.info("导出Excel耗时：" + (end -start) + " 毫秒.");
    }

    /**
     * 保存用户信息
     *
     * @param userVo
     * @return
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(@ModelAttribute UserVo userVo) {
        Map<String, Object> retMap = MessageUtils.success();
        try {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(userVo, userDto);
            new PasswordHelper().encryptPassword(userDto);
            userDto.setCreator(getId());
            userDto.setModifier(getId());
            UserDto bizDto = userService.save(userDto);
            if (bizDto != null && bizDto.getId() != null) {
                List<Long> roleList = userVo.getRoleList();
                if (roleList!= null) {
                    roleList.forEach(roleId -> {
                        UserRoleDto userRoleDto = new UserRoleDto();
                        userRoleDto.setUserId(bizDto.getId());
                        userRoleDto.setRoleId(roleId);
                        userRoleService.save(userRoleDto);
                    });
                    retMap = MessageUtils.success("保存成功");
                    return retMap;
                }
            } else {
                retMap = MessageUtils.error("保存失败");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据ID查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/get/{id}")
    @ResponseBody
    public Map<String, Object> get(@PathVariable("id") Long id) {
        Map<String, Object> retMap = MessageUtils.success();
        try {
            UserDto userDto = userService.getUserById(id);
            if (userDto != null) {
                // 查询所有的角色列表
                List<RoleDto> roleDtos = roleService.getRoleByParam(null);
                // 查询用户的角色列表
                List<Long> roleIds = userRoleService.getRoleIdsByUserId(userDto.getId());
                for (RoleDto roleDto : roleDtos) {
                    Iterator<Long> iterator = roleIds.iterator();
                    while (iterator.hasNext()) {
                        Long roleId = iterator.next();
                        if (roleId.equals(roleDto.getId())) {
                            roleDto.setChecked(true); // 选中
                        }
                    }
                }
                userDto.setRoleDtos(roleDtos);
                retMap.put("userDto", userDto);
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 修改用户信息
     *
     * @param userVo
     * @return
     */
    @PostMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(@ModelAttribute UserVo userVo) {
        Map<String, Object> retMap = null;
        try {
            UserDto userDto = userService.getUserById(userVo.getId());
            if (userDto == null) {
                retMap = MessageUtils.error("修改失败");
                return retMap;
            }
            BeanUtils.copyProperties(userVo, userDto);
            userDto.setModifier(getId());
            // 修改用户
            if (userService.update(userDto) == 1) {
                // 修改用户的角色
                userRoleService.deleteOrSave(userDto.getId(), userVo.getEditRoleList());
                retMap = MessageUtils.success("修改成功");
                List<Long> ids = new ArrayList<>();
                ids.add(userDto.getId());
                // 删除左侧菜单缓存
                asyncTask.deleteLeftCache(ids);
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据ID批量删除用户信息
     *
     * @param ids
     * @return
     */
    @PostMapping(value = "/deleteBatch")
    @ResponseBody
    public Map<String, Object> deleteBatch(@RequestParam("ids[]") List<String> ids) {
        Map<String, Object> retMap = null;
        try {
            // 删除用户
            if (userService.deleteBatchIds(ids)) {
                // 删除用户关联的角色
                ids.stream().forEach(id -> {
                    userRoleService.deleteUserRoleByUserId(Long.valueOf(id));
                });
                retMap = MessageUtils.success("删除成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据用户ID删除用户信息
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete/{id}")
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") Long id) {
        Map<String, Object> retMap = null;
        try {
            // 删除用户
            if (userService.deleteById(id)) {
                // 删除用户关联的角色
                userRoleService.deleteUserRoleByUserId(id);
                retMap = MessageUtils.success("删除成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据ID批量锁定用户信息
     *
     * @param ids
     * @return
     */
    @PostMapping(value = "/lockBatch")
    @ResponseBody
    public Map<String, Object> lockBatch(@RequestParam("ids[]") List<String> ids) {
        Map<String, Object> retMap = null;
        try {
            // 锁定用户
            if (userService.lockBatchIds(ids)) {
                retMap = MessageUtils.success("锁定成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }
    /**
     * 根据ID批量解锁用户
     *
     * @param ids
     * @return
     */
    @PostMapping(value = "/unlockBatch")
    @ResponseBody
    public Map<String, Object> unlockBatch(@RequestParam("ids[]") List<String> ids) {
        Map<String, Object> retMap = null;
        try {
            // 解锁用户
            if (userService.unlockBatchIds(ids)) {
                retMap = MessageUtils.success("解锁成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据ID批量重置用户密码
     *
     * @param ids
     * @return
     */
    @PostMapping(value = "/reset")
    @ResponseBody
    public Map<String, Object> reset(@RequestParam("ids[]") List<String> ids) {
        Map<String, Object> retMap = null;
        try {
            // 重置密码
            if (userService.resetBatchIds(ids)) {
                retMap = MessageUtils.success("重置密码成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

}
